package com.example.store.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.store.common.BaseContext;
import com.example.store.common.IpUtil;
import com.example.store.common.Result;
import com.example.store.entity.Time;
import com.example.store.entity.User;
import com.example.store.service.TimeService;
import com.example.store.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Map;

//用户相关操作
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private TimeService timeService;

    @Autowired
    private ServletContext application;

    //用于记录操作
    private void makeTime(String id, HttpServletRequest request, String operate){
        Time time = Time.createTime(id, 4);
        String ip = IpUtil.getIp(request);
        time.setIp(ip);
        time.setOperate(operate);
        timeService.save(time);
    }

    //用手机号登录，如果不存在则创建新账号
    @PostMapping("/login")
    public Result<String> login(@RequestBody User user, HttpServletRequest request){
        if(user==null||user.getId()==null||user.getPwd()==null||user.getId().equals("")||user.getPwd().equals("")){
            return Result.error("请输入手机号及密码");
        }
        String welcome = "欢迎登陆";
        user.setId("u"+user.getId());

        User user1 = userService.getById(user.getId());
        if(user1 == null){
            user1 = new User();
            user1.setId(user.getId());
            user1.setPwd(user.getPwd());

            makeTime(user1.getId(), request, "首次创建用户账号");
            userService.save(user1);
            welcome = "欢迎注册，请尽快完善个人信息";
        }
        else{
            if(!user.getPwd().equals(user1.getPwd())){
                return Result.error("密码错误");
            }
        }

        //记录最后一次登录时间
        user1.setLastlogin(LocalDateTime.now());
        userService.updateById(user1);

        BaseContext.setCurrentId(user1.getId());

        if(request.getSession().getAttribute("user")==null){
            listenUserCount();
        }

//        记录日志
        Time time = Time.createTime(user1.getId(), 0);
        String ip = IpUtil.getIp(request);
        time.setIp(ip);
        request.getSession().setAttribute("ip", ip);
        timeService.save(time);
        request.getSession().setAttribute("user", user1.getId());

        return Result.success(welcome);
    }

//    游客登录
    @GetMapping("/guest")
    public Result<String> guest(HttpServletRequest request){

        if(request.getSession().getAttribute("user")==null){
            listenUserCount();
        }

        request.getSession().setAttribute("user", "guest");

        return Result.success("游客登录");
    }

//    增加在线人数
    private void listenUserCount() {
        Integer count = (Integer) application.getAttribute("sessions");
        if (count==null){
            application.setAttribute("sessions", 0);
            count=0;
        }
        count++;
        application.setAttribute("sessions", count);
        System.out.println("--------------create    "+count+"    ---------------");
    }

//    获取用户信息
    @GetMapping("/info")
    public Result<User> info(){
//        用户校验
        String id = BaseContext.getCurrentId();
        if(id==null){
            return Result.error("你咋回事");
        }
        if(id.equals("guest")){
            return Result.error("未登录，不登录直接以游客身份访问？");
        }
        User user = userService.getById(id);

//        隐藏密码
        user.setPwd("none");
        return Result.success(user);
    }

//    登出
    @PostMapping("/logout")
    public Result<String> logout(HttpServletRequest request){
//        用户校验
        String id = BaseContext.getCurrentId();
        if(id!=null){
            if(!id.equals("guest")){
                Time time = Time.createTime(id, 1);
                time.setIp(IpUtil.getIp(request));
                timeService.save(time);
            }

//            更新在线人数
            Integer count = (Integer) application.getAttribute("sessions");
            if (count==null||count==0){
                if(count==null){
                    application.setAttribute("sessions", 0);
                }
                return Result.success("欢迎下次再来");
            }
            count--;
            application.setAttribute("sessions", count);
            System.out.println("--------------destroy    "+count+"    ---------------");

            request.getSession().removeAttribute("user");
            request.getSession(false).invalidate();
        }
        return Result.success("欢迎下次再来");
    }

//    更新用户信息
    @PostMapping("/update")
    public Result<User> update(@RequestBody User user, HttpServletRequest request){
//        用户校验
        String id = BaseContext.getCurrentId();
        if(id==null){
            return Result.error("请先登录！");
        }
        user.setId(id);
        if(user.getName()==null||user.getAddress()==null||user.getEmail()==null){
            return Result.error("不能为空");
        }
        else if(user.getAddress().length()<1||user.getName().length()<1||user.getEmail().length()<1){
            return Result.error("不能为空");
        }
        user.setPwd(null);
        userService.updateById(user);
        user.setPwd("none");

        //记录操作
        makeTime(user.getId(), request, "修改用户账号");

        return Result.success(user);
    }

    //管理员查看当前在线人数
    @GetMapping("/count")
    public Result<Integer> count(){
//        用户校验
        String userId = BaseContext.getCurrentId();
        if(userId==null||!userId.equals("root")){
            return Result.error("请管理员登录");
        }
        Integer count = (Integer) application.getAttribute("sessions");
        if(count==null){
            count = 0;
        }

        return Result.success(count);
    }

    //为管理员提供用户分页
    @PostMapping("/page")
    public Result<Page<User>> page(@RequestBody Map<String, String> pageNum){
//        用户校验
        String userId = BaseContext.getCurrentId();
        if(userId==null||!userId.equals("root")){
            return Result.error("请管理员登录");
        }

        if(pageNum.get("pageNum")==null){
            return Result.error("无效页码");
        }
        Page<User> pageInfo = new Page<>(Integer.parseInt(pageNum.get("pageNum")), 10);
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
//        按上次登录时间排序
        queryWrapper.orderByDesc(User::getLastlogin);

        userService.page(pageInfo, queryWrapper);

        for(int i=0;i<pageInfo.getRecords().size();i++){
            pageInfo.getRecords().get(i).setPwd("none");
        }

        return Result.success(pageInfo);
    }

//    为提供管理员信息
    @PostMapping("/infoForAdmin")
    public Result<User> infoForAdmin(@RequestBody User user){
//用户校验
        String userId = BaseContext.getCurrentId();
        if(userId==null||!userId.equals("root")){
            return Result.error("请管理员登录");
        }

        User user1 = userService.getById(user.getId());
        if(user1==null){
            return Result.error("无");
        }
        user1.setPwd("none");

        return Result.success(user1);
    }
}
